/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.event;

import java.util.Hashtable;

import cgl.narada.util.ByteUtilities;

/**
 * The EventID is an ID which is unique in space and time. Using the event ID
 * we can decipher if the event was an earlier event or a later event. This 
 * is what provides us with information pertaining to duplicate detection.
 *
 * @author Shrideep Pallickara
 * $Revision$
 * $Date$
 */

public class EventID {
  /** Every issuing entity is assigned a unique ID. This reduces the uniqueness
      problem to a point in space */
  private int entityID;

  /** The time in milli-seconds  */ 
  private long timeStamp;
  /** We use this so that our issue rate isn't determined by the granularity
      of the clock in the underlying system. The sequence numbers start from
      zero and continue till it reaches Short.MAX_VALUE
  */
  private int seqNum;

  private int eventHashcode = 0;
  
  /** This constructor provides for the unmarshalling of the eventID bytes
      that are received over a link
      @param idBytes A byte stream representation of the event ID.
  */
  public EventID(byte[] idBytes) {
    int offset=0;
    /** UnMarshall the entityID */
    byte[] entityBytes = new byte[4];
    System.arraycopy(idBytes,offset, entityBytes,0,4);
    offset+=4;
    entityID = ByteUtilities.getInt(entityBytes);

    /** UnMarshall the timeStamp */
    byte[] timeStampBytes = new byte[8];
    System.arraycopy(idBytes,offset, timeStampBytes,0,8);
    offset+=8;
    timeStamp = ByteUtilities.getLong(timeStampBytes);

    /** UnMarshall the sequence Number */
    byte[] seqNumBytes = new byte[4];
    System.arraycopy(idBytes,offset, seqNumBytes,0,4);
    offset+=4;
    seqNum = ByteUtilities.getInt(seqNumBytes);
    
    generateEventHashcode();
  }
  
  /** Constructs a unique EventID based on the entityID, timeStamp,
      sequenceNumber and the incarnation associated with the publishing
      entity.
      @param _entityID The entityID
      @param _timeStamp The timestamp associated with the ID.
      @param _seqNum The sequence number
  */
  public EventID(int _entityID, long _timeStamp, int _seqNum ) {
    entityID = _entityID;
    timeStamp = _timeStamp;
    seqNum    = _seqNum;
    generateEventHashcode();
  }
  
  /** Returns the entity ID contained in the eventID 
      @return int entityID */
  public int getEntityID() {
    return entityID;
  }
  
  /** This method returns the timeStamp that is associated with the eventID.
      @return long timeStamp  */
  public long getTimeStamp() {
    return timeStamp;
  }
  
  /** This method returns the sequence number associated with the eventID
      instance.
      @return int sequenceNumber */
  public int getSequenceNumber() {
    return seqNum;
  }
  
  /* Returns a string representation of the EventID object.
     @return String stringRepOfObject */
  public String toString() {
    String stringRep = "Event ID:: entityID -> " + entityID + 
      "  timeStamp -> " + timeStamp + " seqNum -> " + seqNum;
    return stringRep;    
  }
  
  
  /** This method provides a marshalling of the eventID bytes. 
      @return Byte stream representation of the eventID.
  */
  public byte[] getBytes() {
    byte[] idBytes = new byte[4 /* Entity-ID */ + 8 /* Time Stamp */ +
			     4 /*Sequence Num*/ ];
    int offset=0;
    byte[] entityBytes = ByteUtilities.getBytes(entityID);
    byte[] timeStampBytes = ByteUtilities.getBytes(timeStamp);
    byte[] seqNumBytes = ByteUtilities.getBytes(seqNum);

    
    /** Marshall the entity ID */
    System.arraycopy(entityBytes,0, idBytes, offset, 4);
    offset+=4;
    /** Marshall the timeStamp*/
    System.arraycopy(timeStampBytes,0, idBytes, offset, 8);
    offset+=8;
    /** Marshall the sequenceNum */
    System.arraycopy(seqNumBytes,0, idBytes, offset, 4);
    offset+=4;
    return idBytes;  
    
  }



  /**
     Compares two objects for equality. Returns a boolean that indicates
     whether this object is equivalent to the specified object. This method
     is used when an object is stored in a hashtable.
     @param obj the Object to compare with
     @return true if these Objects are equal; false otherwise.
     @see java.util.Hashtable */
  public boolean equals(Object obj) {
    EventID compareWith = (EventID)obj;
    if (entityID == compareWith.getEntityID()) {
      if (timeStamp == compareWith.getTimeStamp()) {
	if (seqNum == compareWith.getSequenceNumber()) {
	  return true;
	}
      }
    }
    return false;
  }

  /**Generates a hash code for the receiver. This method is supported 
     primarily for hash tables, such as those provided in java.util.
     If two objects are equal (equals(Object) returns true) they must have the 
     same hash code
     @return an integer hash code for the receiver */
  public int hashCode() {
    return eventHashcode;
  }

  private void generateEventHashcode() {
    String hashString = "" + entityID + timeStamp + seqNum;
    eventHashcode = hashString.hashCode();
  }

  public static void main(String[] args) {
    String module = "EventID.main() ->" ;
    EventID eventId =  new EventID(123, (long)345, 324);
    EventID eventId2 = new EventID(eventId.getBytes());
    
    if (eventId.equals(eventId2)) {
      System.out.println(module + eventId + "==" + eventId2);
    }

    EventID eventId3 = new EventID(123, (long)345, 323);
    Hashtable evtTable = new Hashtable();
    evtTable.put(eventId, eventId);
    evtTable.put(eventId3, eventId3);

    System.out.println(module + evtTable.get(eventId3) );
    System.out.println(module + evtTable.get(eventId) );
  }
}



